package com.zhuhjay.boot.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhuhjay.boot.mapper.OrderMapper;
import com.zhuhjay.boot.mapper.SetmealMapper;
import com.zhuhjay.constant.RedisConstant;
import com.zhuhjay.domain.entity.Order;
import com.zhuhjay.domain.entity.Setmeal;
import com.zhuhjay.domain.http.PageResult;
import com.zhuhjay.domain.http.QueryPageBean;
import com.zhuhjay.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zhuhjay
 * @since 2022-04-02
 */
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private Configuration configuration;

    @Autowired
    private OrderMapper orderMapper;

    @Value("${custom.out-put-template-path}")
    private String outPutTemplatePath;

    @Override
    public void add(Integer[] ids, Setmeal setmeal) {
        baseMapper.insert(setmeal);
        // 将套餐和检查组进行关联
        if( ids != null && ids.length > 0 ){
            for (Integer id : ids) {
                baseMapper.addRelationAndCheckgroup(setmeal.getId(), id);
            }
        }
        // 将此时新增的信息的图片存储到redis
        redisTemplate.opsForSet().add(RedisConstant.SETMEAL_PIC_DB_RESOURCES, setmeal.getImg());

        generateMobileStaticHtml();
    }

    //生成静态页面
    private void generateMobileStaticHtml() {
        List<Setmeal> setmeals = baseMapper.selectList(null);
        generateMobileSetmealListHtml(setmeals);
        generateMobileSetmealDetailHtml(setmeals);
    }

    //生成套餐列表静态页面
    private void generateMobileSetmealListHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        map.put("setmealList", setmealList);
        generateHtml(
                "mobile_setmeal.ftl",
                "m_setmeal.html", map);
    }

    //生成套餐详情静态页面（多个）
    private void generateMobileSetmealDetailHtml(List<Setmeal> setmealList) {
        Map<String, Object> map = new HashMap<>();
        setmealList.forEach(setmeal -> {
            map.put("setmeal", findAllTableInfoBySetmealId(setmeal.getId()));
            generateHtml(
                    "mobile_setmeal_detail.ftl",
                    "setmeal_detail_" + setmeal.getId() + ".html",
                    map);
        });
    }

    // 生成静态文件
    private void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap){
        Writer out = null;
        try {
            // 根据模板名称获取模板数据
            Template template = configuration.getTemplate(templateName);
            // 创建输出流
            out = new FileWriter(outPutTemplatePath + "/" + htmlPageName);
            // 将生成静态文件到指定位置
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if( out != null ){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        Page<Setmeal> page = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        String queryString = queryPageBean.getQueryString();
        QueryWrapper<Setmeal> queryWrapper = new QueryWrapper<>();
        if( queryString != null && queryString.trim().length() > 0 ){
            queryWrapper
                    .eq("code", queryString)
                    .or()
                    .eq("name", queryString);
        }
        IPage<Setmeal> selectPage = baseMapper.selectPage(page, queryWrapper);
        return new PageResult(selectPage.getTotal(), selectPage.getRecords());
    }

    @Override
    public Setmeal findAllTableInfoBySetmealId(Integer id) {
        return baseMapper.findAllAndCheckGroup(id);
    }

    @Override
    public Map<String, Object> getReport() {
        Map<String, Object> map = new HashMap<>();
        List<String> setmealNames = new ArrayList<>();
        List<Map<String, Object>> setmealCount = new ArrayList<>();

        // 获取到所有的套餐信息
        List<Setmeal> setmeals = baseMapper.selectList(null);
        setmeals.forEach(setmeal -> {
            Map<String, Object> dataMap = new HashMap<>();
            // 记录套餐名称
            setmealNames.add(setmeal.getName());
            // 通过套餐的id获取订单数量
            Integer count = orderMapper.selectCount(new QueryWrapper<Order>()
                        .eq("setmeal_id", setmeal.getId()));
            dataMap.put("name", setmeal.getName());
            dataMap.put("value", count);
            setmealCount.add(dataMap);
        });
        map.put("setmealNames", setmealNames);
        map.put("setmealCount", setmealCount);
        return map;
    }

}
